import React,{ Component } from 'react';
import { 
	StyleSheet, 
	View, 
	Text, 
	Image,
	FlatList,
	TouchableOpacity,
    TouchableHighlight,
    Alert 
} from 'react-native';
import StorageUtil from '../../common/storageUtil';
import SwipeableFlatList from '../../common/FixSwipeadFlatList';
import Toast, {DURATION} from 'react-native-easy-toast';
import { HeaderDatepicker } from '../../common';
import Picker from 'react-native-picker';
import Axios from '../../axios';
import NoDataPage from '../../common/NoDataPage';
class HeaderLeft extends Component{


	componentDidMount(){
		// console.log(Picker)
		// let data = [];
		// for(var i=0;i<100;i++){
		//     data.push(i);
		// }

		// Picker.init({
		//     pickerData: data,
		//     selectedValue: [59],
		//     onPickerConfirm: data => {
		//         console.log(data);
		//     },
		//     onPickerCancel: data => {
		//         console.log(data);
		//     },
		//     onPickerSelect: data => {
		//         console.log(data);
		//     }
		// });
		// Picker.show();
	}

	pickerShow = ()=>{
        Picker.init({
            pickerData: [
                {
                  北京:[
                          {
                              朝阳区:['艾欧尼亚','暗影岛']
                          },
                          {
                              东城区:['艾欧尼亚2','暗影岛2']
                          }
                         ]
                },

                {
                    重庆:[
                        {
                            渝北区:['光电园','嘉州']
                        },
                        {
                            江北区:['观音桥','华新街']
                        }
                    ]
                },

            ],
            selectedValue: ['重庆','渝北区','嘉州'],
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText: '',
            pickerConfirmBtnColor: [245, 69, 69, 1],
    		pickerCancelBtnColor: [245, 69, 69, 1],
            pickerToolBarBg: [255, 255, 255, 1],
            pickerBg:[255, 255, 255, 1],
            pickerToolBarFontSize: 16,
            pickerFontSize: 20,
            onPickerConfirm: (data) => {
                // console.log(data)
                
            }
        });
        Picker.show();
    }

	render(){
		return(
			<TouchableOpacity onPress={()=>this.pickerShow()}>
				<View style={styles.topLeftWraper}>
					<Image
						style={styles.topLeftImg}
						source={require('../../assets/images/area_icon.png')}
					/>
					<Text
						style={styles.topLeftTxt}
					>全省</Text>
				</View>
			</TouchableOpacity>
		)
	}
}

class HeaderRight extends Component{
	render(){
		return(
			<TouchableOpacity>
				<Image 
					style={styles.topRightImg}
					source={require('../../assets/images/plus_icon.png')} 
				/>
			</TouchableOpacity>
		)
	}
}



export default class TrackCommon extends Component{
	constructor(props) {
	   super(props);
	   this.state = {
			reportList:[],
			isRefresh:true,
			showRoleData:[],
			createUserId:0,
		}
	   let _this = this;
	   StorageUtil.getItem(global.Constants.USER_ROLEDATA).then((val)=>{
			let  showRoleData = [];
			val.map(
                (element,index)=>{
            		if(element.dataResValue.indexOf('ACTIVITY_APPROVE_TYPE')>-1){
						   let val = element.dataResValue.replace('ACTIVITY_APPROVE_TYPE=','');
						   showRoleData.push(val);
            		}
                });
           _this.setState({showRoleData:showRoleData});
		});
	    StorageUtil.getItem(global.Constants.USER_INFO).then((val)=>{
			_this.setState({createUserId:val.createUserId});
		});
	}
	static navigationOptions = ({navigation,navigationOptions})=>{
		return {
			title:"首页",
			headerTitle:<HeaderDatepicker />,
			headerStyle:{
				...navigationOptions.headerStyle,
				backgroundColor:"#f54545"
			},
			headerLeft:<HeaderLeft onPress={()=>navigation.goBack()} />,
			headerRight:<HeaderRight />
		}
	}

	getReportList = ()=>{
		const routeName = this.props.navigation.state.routeName;
		let url = ''
		let activityStatus;
		if(routeName === 'StartedActivity'){
			url = '/mkt/searchActivity';
			activityStatus='4';
		}else if(routeName === 'CloseActivity'){
			url = '/mkt/searchActivity';
			activityStatus='8';
		}else{
			url = '/mkt/searchActivity';
			activityStatus='1';
		}
		
		Axios.ajax({
			url:url,
			data:{'activityStatus':activityStatus}
		}).then((res)=>{
			//console.log(res)
			this.setState({reportList:res.data,isRefresh:false})
		})
	}


	setApprove = (relId,approve)=>{
		
		Axios.ajax({
			url:'/mkt/approve',
			data:{'relId':relId,'approve':approve}
		}).then((res)=>{
			//console.log(res)
			this.setState({isRefresh:false})
			if(typeof(res.data) == "undefined"){
				this.refs.toast.show(res,3);
			}else{
				this.refs.toast.show(res.data,3);
			}
			
			this.onRefresh();
		})
	}

	setOperation = (relId,status)=>{
		Axios.ajax({
			url:'/mkt/operation',
			data:{'relId':relId,'status':status}
		}).then((res)=>{
			//console.log(res)
			this.setState({isRefresh:false})
			this.refs.toast.show(res.data,3);
			this.onRefresh();
		})
	}
	//componentWillMount(){
	//	this.getReportList();
	//}
	onRefresh = ()=>{
		this.getReportList();
	}
	componentDidMount() {
		 //console.log(this.refs)
		 //this.refs.toast.show('网络加载中...');
	     this.subs = [this.props.navigation.addListener('didFocus', () => this.getReportList()),];
	}

	componentWillUnmount() {
	     this.subs.forEach(sub => sub.remove());
	}



	  _renderItem({item}) {
	    return (
	      <View style={styles.reportCellWrap}>
			    	<View style={styles.reportHeaderWrap}>
			    		<View style={styles.reportHeaderTitle}>
			    			<Image 
								style={styles.reportHeaderImg}
			    				source={require('../../assets/images/daily_report.png')} />
			    			<Text style={styles.reportHeaderTxt}>{item.activityName}</Text>
			    		</View>
			    	
			    	</View>
			    	<View style={styles.reportCellContentWrap}>
			  
			    		<Text style={styles.reportContentTotal}>{item.successRate}<Text style={styles.reportContentUnit}>%</Text></Text>
			    		<View style={styles.reportContentBottomWrap}>
			    			<Text style={styles.reportContentBottomTxt}>{`派单量：${item.sendAllCnt}`}</Text>
			    			<Text style={styles.reportContentBottomTxt}>{`触发量：${item.sendSuccessCnt}`}</Text>
			    			<Text style={styles.reportContentBottomTxt}>{`办理量：${item.transactSuccessCnt}`}</Text>
			    		</View>
			    		<View style={styles.reportContentBottomWrap}>
			    			<Text style={styles.reportContentBottomTxt}>{`创建人：${item.staffName}`}</Text>
			    			<Text style={styles.reportContentBottomTxt}>{`状态：${item.activityStatusName}`}</Text>
			    			<Text style={styles.reportContentBottomTxt}>{`渠道：${item.channelName}`}</Text>
			    		</View>
			    	</View>
			    	
			    </View>

	    );
  	}


	 _renderQuickActions({item}) {
	 	const routeName = this.props.navigation.state.routeName;
	 	if(routeName === 'StartedActivity'){
	 		return (
		      <View style={styles.quickAContent}>
		    	<TouchableHighlight
		          onPress={() => {
		          	if(item.staffId==this.state.createUserId||this.state.showRoleData.includes(item.activityType)){
			            Alert.alert(
			              '提示',
			              '确定要关闭活动吗？',
						  [
						    {text: '确定', onPress: () => {
						    	this.setOperation(item.relId,'8');
						    	this._flatListRef._onClose()
						    }},
						    {text: '取消', onPress: () => console.log('OK Pressed')}
						  ],
						  { cancelable: false }
			            );
			        }else{
						this.refs.toast.show('暂无操作权限',3);
					 }
		          }}>
		          <View style={[styles.quick,styles.gray]}>
		          	<Text style={styles.quickTxt}>关闭</Text>
		          </View>
		        </TouchableHighlight>
		        <TouchableHighlight
		          onPress={() => {
		          	if(item.staffId==this.state.createUserId||this.state.showRoleData.includes(item.activityType)){
			            Alert.alert(
			              '提示',
			              '确定要暂停活动吗？',
						  [
						    {text: '确定', onPress: () => {
						    	this.setOperation(item.relId,'5');
						    	this._flatListRef._onClose()
						    }},
						    {text: '取消', onPress: () => console.log('OK Pressed')}
						  ],
						  { cancelable: false }
			            );
			         }else{
						this.refs.toast.show('暂无操作权限',3);
					 }
		          }}>
		          <View style={styles.quick}>
		          	<Text style={styles.quickTxt}>暂停</Text>
		          </View>
		        </TouchableHighlight>
		      </View>
		    );
	 	}else if(routeName === 'ApprovalPending'){
	 		return (
		      <View style={styles.quickAContent}>
		        <TouchableHighlight
		          onPress={() => {
                	 if(this.state.showRoleData.includes(item.activityType)){
			            Alert.alert(
						  '审核',
						  '是否通过审核？',
						  [
						  	{text: '同意', onPress: () => {
						    	this.setApprove(item.relId,'1');
						    	this._flatListRef._onClose()
						    }},
						  	{text: '不同意', onPress: () => {
						    	this.setApprove(item.relId,'0');
						    	this._flatListRef._onClose()
						    }},
						    {text: '取消', onPress: () => console.log('OK Pressed')}
						  ],
						  { cancelable: false }
						)
					 }else{
						this.refs.toast.show('暂无操作权限',3);
					 }
		          }}>
		          <View style={[styles.quick,styles.gray]}>
		          	<Text style={styles.quickTxt}>审批</Text>
		          </View>
		        </TouchableHighlight>
		        <TouchableHighlight
		          onPress={() => {
		          	console.log(item.staffId+'#'+item.activityType+'#'+this.state.showRoleData+'#'+this.state.createUserId);
		            if(item.staffId==this.state.createUserId||this.state.showRoleData.includes(item.activityType)){
			             Alert.alert(
			               '提示',
			               '确定要删除活动吗？',
						   [
						     {text: '确定', onPress: () => {
						     		this.setOperation(item.relId,'6');
						     		this._flatListRef._onClose()
						     }},
						     {text: '取消', onPress: () => console.log('OK Pressed')}
						   ],
						   { cancelable: false }
			             );
		             }else{
						this.refs.toast.show('暂无操作权限',3);
					 }
		          }}>
		          <View style={styles.quick}>
		          	<Text style={styles.quickTxt}>删除</Text>
		          </View>
		        </TouchableHighlight>
		      </View>
		    );
	 	}else{
	 		return (
		      <View style={styles.actionsContainer}>
		      </View>
		    );
	 	}
	  }

	_onClose(key: any): void {
	    this.setState({
	      openRowKey: null,
	    });
	}
	render(){
		const routeName = this.props.navigation.state.routeName;
		let  btnCount = 0;
		if(routeName === 'StartedActivity'){
			btnCount = 160;
		}else if(routeName === 'CloseActivity'){
			btnCount = 0;
		}else{
			btnCount = 160;
		}
		return(
			<View style={styles.container}>
				<SwipeableFlatList
					ref={ref => {
					    this._flatListRef = ref;
					}}
    				data={this.state.reportList}
          			bounceFirstRowOnMount={false}
          			maxSwipeDistance={btnCount}
          			renderItem={this._renderItem.bind(this)}          	
          			renderQuickActions={this._renderQuickActions.bind(this)}
          			bounceFirstRowOnMount={false}//进去的时候不展示侧滑效果
          			refreshing={this.state.isRefresh}
          			onRefresh={() => this.onRefresh()}
          			ListEmptyComponent={<NoDataPage text="暂无此类活动"/>}
				/>
				<Toast 
					ref="toast"  
					position="bottom"
					positionValue={260}
					fadeInDuration={750}
                    fadeOutDuration={1000}
                    opacity={0.8}
				/>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container : {
		flex : 1,
		backgroundColor:'#f5f5f5'
	},
	textColor:{
		color:'#f00'
	},
	topLeftWraper:{
		flex:1,
		flexDirection:'row',
		justifyContent:'center',
		alignItems:'center'
	},
	topLeftImg:{
		width:22,
		height:22,
		marginLeft:10
	},
	topLeftTxt:{
		color:'#fff',
		fontSize:16,
		marginLeft:5
	},
	topRightImg:{
		width:22,
		height:22,
		marginRight:10
	},
	reportCellWrap:{
		backgroundColor:"#fff",
		marginTop:8
	},
	reportHeaderWrap:{
		flex:1,
		flexDirection:'row',
		alignItems:"center",
		padding:10,
		borderBottomWidth:1,
		borderBottomColor:"#f7f7f7"
	},
	reportHeaderTitle:{
		flex:1,
		flexDirection:'row',
		alignItems:"center"
	},
	reportHeaderImg:{
		width:16,
		height:18,
		marginRight:5
	},
	reportHeaderTxt:{
		fontSize:14
	},
	reportHeaderRightIcon:{
		width:16,
		height:18
	},
	reportCellContentWrap:{
		flex:1,
		justifyContent:"center",
		marginTop:20,
		marginBottom:20
	},
	reportContentTopTxt:{
		textAlign:"center",
		fontSize:14
	},
	reportContentTotal:{
		textAlign:"center",
		fontSize:26,
		color:"#f54545",
		marginTop:10,
		marginBottom:10
	},
	reportContentUnit:{
		fontSize:12,
		fontWeight:"bold"
	},
	reportContentBottomWrap:{
		flex:1,
		flexDirection:"row",
		justifyContent:"center"
	},
	reportContentBottomTxt:{
		fontSize:14,
		marginRight:10,
		marginLeft:10
	},
	row: {
	    flexDirection: 'row',
	    justifyContent: 'center',
	    alignItems: 'center',
	    padding: 10,
	    backgroundColor: '#F6F6F6',
    },
  //侧滑菜单的样式
	quickAContent:{
	    flex:1,
	    flexDirection:'row',
	    justifyContent:'flex-end'
	},
	gray:{
		backgroundColor:"#ccc",
	},
	quick:{
	    backgroundColor:"#f54545",
	    flex:1,
	    alignItems:'center',//水平靠右
	    justifyContent:'center',//上下居中
	    width:80,
	    marginTop:10

	},
	quickTxt:{
	    color:"#fff",
	    fontSize:18
	},
  rowIcon: {
    width: 64,
    height: 64,
    marginRight: 20,
  },
  rowData: {
    flex: 1,
  },
  rowDataText: {
    fontSize: 24,
  },
  actionsContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  actionButton: {
    padding: 10,
    width: 80,
    backgroundColor: '#999999',
  },
  actionButtonDestructive: {
    backgroundColor: '#FF0000',
  },
  actionButtonText: {
    textAlign: 'center',
  }

})